﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 车辆交易评价表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppVehicleTransactionFeedbackService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppVehicleTransactionFeedback> _appVehicleTransactionFeedbackRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly UserManager _userManager;

    public AppVehicleTransactionFeedbackService(SqlSugarRepository<AppVehicleTransactionFeedback> appVehicleTransactionFeedbackRep, ISqlSugarClient sqlSugarClient, UserManager userManager)
    {
        _appVehicleTransactionFeedbackRep = appVehicleTransactionFeedbackRep;
        _sqlSugarClient = sqlSugarClient;
        _userManager = userManager;

    }

    /// <summary>
    /// 分页查询车辆交易评价表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询车辆交易评价表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppVehicleTransactionFeedbackOutput>> Page(PageAppVehicleTransactionFeedbackInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appVehicleTransactionFeedbackRep.AsQueryable()
            .WhereIF(input.TransactionId != null, u => u.TransactionId == input.TransactionId)
            .WhereIF(input.TransactionType.HasValue, u => u.TransactionType == input.TransactionType)
            .WhereIF(input.EvaluatorId != null, u => u.EvaluatorId == input.EvaluatorId)
            .WhereIF(input.TargetUserId != null, u => u.TargetUserId == input.TargetUserId)
            .WhereIF(input.FeedbackRole.HasValue, u => u.FeedbackRole == input.FeedbackRole)
            .LeftJoin<AppVehiclePurchase>((u, transaction) => u.TransactionId == transaction.Id)
            .LeftJoin<SysUser>((u, transaction, evaluator) => u.EvaluatorId == evaluator.Id)
            .LeftJoin<SysUser>((u, transaction, evaluator, targetUser) => u.TargetUserId == targetUser.Id)
            .Select((u, transaction, evaluator, targetUser) => new AppVehicleTransactionFeedbackOutput
            {
                Id = u.Id,
                TransactionId = u.TransactionId,
                TransactionFkDisplayName = $"{transaction.BrandId}",
                TransactionType = u.TransactionType,
                EvaluatorId = u.EvaluatorId,
                EvaluatorFkDisplayName = $"{evaluator.RealName}",
                TargetUserId = u.TargetUserId,
                TargetUserFkDisplayName = $"{targetUser.RealName}",
                FeedbackRole = u.FeedbackRole,
                Rating = u.Rating,
                Comment = u.Comment,
                Images = u.Images,
                Tags = u.Tags,
                IsAnonymous = u.IsAnonymous,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 分页查询车辆交易评价表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询车辆交易评价表")]
    [ApiDescriptionSettings(Name = "List"), HttpPost]
    public async Task<List<AppVehicleTransactionFeedbackOutput>> List(VehicleTransactionFeedbackUserInput input)
    {
        var query = _appVehicleTransactionFeedbackRep.AsQueryable()
            .WhereIF(input.TransactionId != null, u => u.TransactionId == input.TransactionId)
            .WhereIF(input.TransactionType.HasValue, u => u.TransactionType == input.TransactionType)
            .WhereIF(input.EvaluatorId != null, u => u.EvaluatorId == input.EvaluatorId)
            .WhereIF(input.TargetUserId != null, u => u.TargetUserId == _userManager.UserId)
            .WhereIF(input.FeedbackRole.HasValue, u => u.FeedbackRole == input.FeedbackRole)
            .LeftJoin<AppVehiclePurchase>((u, transaction) => u.TransactionId == transaction.Id)
            .LeftJoin<SysUser>((u, transaction, evaluator) => u.EvaluatorId == evaluator.Id)
            .LeftJoin<SysUser>((u, transaction, evaluator, targetUser) => u.TargetUserId == targetUser.Id)
            .Select((u, transaction, evaluator, targetUser) => new AppVehicleTransactionFeedbackOutput
            {
                Id = u.Id,
                TransactionId = u.TransactionId,
                TransactionFkDisplayName = $"{transaction.BrandId}",
                TransactionType = u.TransactionType,
                EvaluatorId = u.EvaluatorId,
                EvaluatorFkDisplayName = $"{evaluator.RealName}",
                TargetUserId = u.TargetUserId,
                TargetUserFkDisplayName = $"{targetUser.RealName}",
                FeedbackRole = u.FeedbackRole,
                Rating = u.Rating,
                Comment = u.Comment,
                Images = u.Images,
                Tags = u.Tags,
                IsAnonymous = u.IsAnonymous,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.ToListAsync();
    }

    /// <summary>
    /// 获取车辆交易评价表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取车辆交易评价表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppVehicleTransactionFeedback> Detail([FromQuery] QueryByIdAppVehicleTransactionFeedbackInput input)
    {
        return await _appVehicleTransactionFeedbackRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加车辆交易评价表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加车辆交易评价表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppVehicleTransactionFeedbackInput input)
    {
        var entity = input.Adapt<AppVehicleTransactionFeedback>();
        entity.EvaluatorId = _userManager.UserId;
        return await _appVehicleTransactionFeedbackRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新车辆交易评价表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新车辆交易评价表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppVehicleTransactionFeedbackInput input)
    {
        var entity = input.Adapt<AppVehicleTransactionFeedback>();
        await _appVehicleTransactionFeedbackRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除车辆交易评价表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除车辆交易评价表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppVehicleTransactionFeedbackInput input)
    {
        var entity = await _appVehicleTransactionFeedbackRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appVehicleTransactionFeedbackRep.FakeDeleteAsync(entity);   //假删除
        //await _appVehicleTransactionFeedbackRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除车辆交易评价表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除车辆交易评价表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppVehicleTransactionFeedbackInput> input)
    {
        var exp = Expressionable.Create<AppVehicleTransactionFeedback>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appVehicleTransactionFeedbackRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appVehicleTransactionFeedbackRep.FakeDeleteAsync(list);   //假删除
        //return await _appVehicleTransactionFeedbackRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppVehicleTransactionFeedbackInput input)
    {
        var transactionIdData = await _appVehicleTransactionFeedbackRep.Context.Queryable<AppVehiclePurchase>()
            .InnerJoinIF<AppVehicleTransactionFeedback>(input.FromPage, (u, r) => u.Id == r.TransactionId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.BrandId}"
            }).ToListAsync();
        var evaluatorIdData = await _appVehicleTransactionFeedbackRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppVehicleTransactionFeedback>(input.FromPage, (u, r) => u.Id == r.EvaluatorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        var targetUserIdData = await _appVehicleTransactionFeedbackRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppVehicleTransactionFeedback>(input.FromPage, (u, r) => u.Id == r.TargetUserId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "transactionId", transactionIdData },
            { "evaluatorId", evaluatorIdData },
            { "targetUserId", targetUserIdData },
        };
    }
    
    /// <summary>
    /// 导出车辆交易评价表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出车辆交易评价表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppVehicleTransactionFeedbackInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppVehicleTransactionFeedbackOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "车辆交易评价表导出记录");
    }
    
    /// <summary>
    /// 下载车辆交易评价表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载车辆交易评价表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppVehicleTransactionFeedbackOutput>(), "车辆交易评价表导入模板", (_, info) =>
        {
            if (nameof(ExportAppVehicleTransactionFeedbackOutput.TransactionFkDisplayName) == info.Name) return _appVehicleTransactionFeedbackRep.Context.Queryable<AppVehiclePurchase>().Select(u => $"{u.BrandId}").Distinct().ToList();
            if (nameof(ExportAppVehicleTransactionFeedbackOutput.EvaluatorFkDisplayName) == info.Name) return _appVehicleTransactionFeedbackRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            if (nameof(ExportAppVehicleTransactionFeedbackOutput.TargetUserFkDisplayName) == info.Name) return _appVehicleTransactionFeedbackRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入车辆交易评价表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入车辆交易评价表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppVehicleTransactionFeedbackInput, AppVehicleTransactionFeedback>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 交易ID
                    var transactionIdLabelList = pageItems.Where(x => x.TransactionFkDisplayName != null).Select(x => x.TransactionFkDisplayName).Distinct().ToList();
                    if (transactionIdLabelList.Any()) {
                        var transactionIdLinkMap = _appVehicleTransactionFeedbackRep.Context.Queryable<AppVehiclePurchase>().Where(u => transactionIdLabelList.Contains($"{u.BrandId}")).ToList().ToDictionary(u => $"{u.BrandId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TransactionId = transactionIdLinkMap.GetValueOrDefault(e.TransactionFkDisplayName ?? "");
                            if (e.TransactionId == null) e.Error = "交易ID链接失败";
                        });
                    }
                    // 链接 评价用户ID
                    var evaluatorIdLabelList = pageItems.Where(x => x.EvaluatorFkDisplayName != null).Select(x => x.EvaluatorFkDisplayName).Distinct().ToList();
                    if (evaluatorIdLabelList.Any()) {
                        var evaluatorIdLinkMap = _appVehicleTransactionFeedbackRep.Context.Queryable<SysUser>().Where(u => evaluatorIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.EvaluatorId = evaluatorIdLinkMap.GetValueOrDefault(e.EvaluatorFkDisplayName ?? "");
                            if (e.EvaluatorId == null) e.Error = "评价用户ID链接失败";
                        });
                    }
                    // 链接 被评价用户ID
                    var targetUserIdLabelList = pageItems.Where(x => x.TargetUserFkDisplayName != null).Select(x => x.TargetUserFkDisplayName).Distinct().ToList();
                    if (targetUserIdLabelList.Any()) {
                        var targetUserIdLinkMap = _appVehicleTransactionFeedbackRep.Context.Queryable<SysUser>().Where(u => targetUserIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TargetUserId = targetUserIdLinkMap.GetValueOrDefault(e.TargetUserFkDisplayName ?? "");
                            if (e.TargetUserId == null) e.Error = "被评价用户ID链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.TransactionId == null){
                            x.Error = "交易ID不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.TransactionType == null){
                            x.Error = "交易类型不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.EvaluatorId == null){
                            x.Error = "评价用户ID不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.TargetUserId == null){
                            x.Error = "被评价用户ID不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.FeedbackRole == null){
                            x.Error = "评价角色不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Rating == null){
                            x.Error = "评价分数不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.IsAnonymous == null){
                            x.Error = "是否匿名不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppVehicleTransactionFeedback>>();
                    
                    var storageable = _appVehicleTransactionFeedbackRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Comment), "评价内容不能为空")
                        .SplitError(it => it.Item.Comment?.Length > 500, "评价内容长度不能超过500个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
